﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RTW.Core.Extensions;
using RTW.Models;
using RTW.Servers;
using RTW.Web.Comm;

namespace RTW.Web.Areas.System.Controllers
{
    [Area("System")]
    public class DepartmentController : CommController
    {
        readonly DepartmentServer _departmentServer;
        readonly TOrganizationServer _organizationServer;
        public DepartmentController()
        {
            _departmentServer = new DepartmentServer();
            _organizationServer = new TOrganizationServer();
        }
        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> GetDepartmentTreeJson()
        {
            var treelist =await _departmentServer.GetAllAsync();
            return Json(treelist);
        }

        public async Task<IActionResult> Edit(string ParentID=null,string ID=null)
        {
            TDepartment dpt = new TDepartment();
            //编辑或新增
            if (string.IsNullOrEmpty(ID))
            {
                if (string.IsNullOrEmpty(ParentID))
                {
                    
                }
                else {
                    dpt.PDM = await _departmentServer.GetByOneAsync(ParentID);
                    dpt.ParentID = ParentID;
                }
            }
            else
            {
                //修改时回绑字段
                dpt = await _departmentServer.GetByOneAsync(ID);
            }
            return View(dpt);
        }
        [HttpPost]
        public async Task<IActionResult> Edit(string ID, TDepartment dept)
        {
            //编辑或新增
            if (string.IsNullOrEmpty(ID))
            {
                //新增
                dept.ID = Guid.NewGuid().ToString("N");
                await _departmentServer.InsertAsync(dept);



                AddLog("添加了部门（" + dept.DMName + "）", "组织机构", Request.GetAbsoluteUri());
            }
            else
            {
                //修改
                //org.Parent_ID = org.Bak2;//更新父节点ID
                await _departmentServer.UpdateAsync(dept);

                AddLog("修改了部门（" + dept.DMName + "）", "组织机构", Request.GetAbsoluteUri());
            }
            return Json(MsgResult(true));
        }
        public IActionResult OrgManager(string DMID)
        {
            ViewBag.reurl = HttpContext.Request.GetAbsoluteUri();
            ViewBag.DMID = DMID;
            return View();
        }

        public async Task<IActionResult> GetDepartmentJsonData(string DMID)
        {
            var orderlist = new List<Core.Entity.SortInfo<TOrganization, object>>
            {
                new Core.Entity.SortInfo<TOrganization, object>() { Orderby = m => m.OrgDepartment, SortMethods = Core.Enums.SortEnum.asc },
                new Core.Entity.SortInfo<TOrganization, object>() { Orderby = m => m.Flag1, SortMethods = Core.Enums.SortEnum.asc },
                new Core.Entity.SortInfo<TOrganization, object>() { Orderby = m => m.AddTime, SortMethods = Core.Enums.SortEnum.asc }
            };

            var list = await _organizationServer.GetAsync(m=>m.DMID== DMID&&m.Flag2==1, orderlist); //string.Format("select * from TOrganization where DMID='{0}' and Flag2=1 order by OrgDepartment asc,Flag1 asc,AddTime asc;", DMID);
            return Json(list);

        }


        public async Task<IActionResult> ChangeState(string ID, string ParVal)
        {
            var n = await _organizationServer.ChangeState(ID, ParVal);

            return Json(n);
        }


        public async Task<IActionResult> OrgEdit(string DMID,string ID)
        {
            TOrganization _Org = new TOrganization();
            //编辑或新增
            if (string.IsNullOrEmpty(ID))
            {
                _Org.PDM = _departmentServer.GetByOne(m => m.ID == DMID);
            }
            else
            {
                //修改时回绑字段
                _Org = await _organizationServer.GetByOneAsync(m => m.ID == ID);
                _Org.PDM = _departmentServer.GetByOne(m => m.ID == DMID);
            }

            return View(_Org);
        }
        [HttpPost]
        public async Task<IActionResult> OrgEdit(string ID, TOrganization org)
        {
            try
            {
                if (string.IsNullOrEmpty(ID))
                {
                    //新增
                    org.ID = Guid.NewGuid().ToString("N");
                    org.OrgDepartment = "行政部门";
                    org.Flag2 = 1;
                    org.AddTime = DateTime.Now;
                    await _organizationServer.InsertAsync(org);


                  
                    AddLog("添加了组织机构（" + org.OrgName + "）", "组织机构", Request.GetAbsoluteUri());
                }
                else
                {
                    //修改
                    //org.Parent_ID = org.Bak2;//更新父节点ID
                    await _organizationServer.UpdateAsync(org);

                    AddLog("修改了组织机构（" + org.OrgName + "）", "组织机构", Request.GetAbsoluteUri());
                }

            }
            catch (Exception e)
            {
                AddErrLog(e.Message, UserDMID);
                return Json(MsgResult(false));
            }
            //_context.Clients.All.ShowTips("菜单信息保存成功!", 2);

            // return View();

            return Json(MsgResult(true));
        }

        public async Task< IActionResult> DelDepartment(string ID)
        {
            var success = await _departmentServer.DeleteAsync(ID);
            AddLog("删除了一条数据", "组织机构", Request.GetAbsoluteUri());
            return Json(success);
        }
    }
}